﻿using System;
using KryptecizerBase;

namespace Kryptonalysis.Rank
{
    /// <summary>
    /// List of LetterRanks that fills it self.
    /// </summary>
    public class SelffillingLetterRanks : LetterRanks
    {
        private KryptoText _baseText;

        /// <summary>
        /// Property to get the language.
        /// </summary>
        /// <value>The language.</value>
        public override string Language
        {
            get { return "Unknown"; }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="FrequenceLetterRanks"/> class.
        /// </summary>
        /// <param name="kryptoText">The krypto text.</param>
        public SelffillingLetterRanks(KryptoText kryptoText)
        {
            _baseText = kryptoText;
            AddFrequences();
            CalcRanks();
        }

        /// <summary>
        /// Fills this instance.
        /// </summary>
        protected override void Fill()
        {
            FillSigns();
        }

        /// <summary>
        /// Calcs the ranks.
        /// </summary>
        private void CalcRanks()
        {
            Sort(LetterRankComperison);
            SetRanks();
        }

        /// <summary>
        /// Sets the ranks.
        /// </summary>
        private void SetRanks()
        {
            for (int i = Count - 1; i >= 0; i--)
                (this[i] as FrequenceLetterRank).Rank = i + 1;
        }

        /// <summary>
        /// LetterRank comperison.
        /// </summary>
        /// <param name="item1">The item1.</param>
        /// <param name="item2">The item2.</param>
        /// <returns>the int defining the order of the items</returns>
        private int LetterRankComperison(LetterRank item1, LetterRank item2)
        {
            FrequenceLetterRank i1 = (item1 as FrequenceLetterRank);
            FrequenceLetterRank i2 = (item2 as FrequenceLetterRank);
            return i1.Frequence.CompareTo(i2.Frequence) * -1;
        }

        /// <summary>
        /// Adds the frequences.
        /// </summary>
        private void AddFrequences()
        {
            int asciiIndex;
            string text = _baseText.GetAsString();
            foreach (Char item in text)
            {
                asciiIndex = (int)item;
                if ((asciiIndex <= 122) && (asciiIndex >= 97))
                    asciiIndex -= 32;
                if ((asciiIndex >= 65) && (asciiIndex <= 90))
                    (GetBySign(item) as FrequenceLetterRank).Frequence++;
            }
        }

        /// <summary>
        /// Fills the signs.
        /// </summary>
        private void FillSigns()
        {
            for (int i = 65; i <= 90; i++)
                Add(new FrequenceLetterRank(Convert.ToChar(i)));
        }
    }
}
